import { BrowserWindow, screen, Rectangle } from 'electron'
import path from 'path'
import http from 'http'
import fs from 'fs'

interface SharedObject {
    isDev: boolean,
    serverPort: number
};

let sharedObject: SharedObject = {
    isDev: process.env.NODE_ENV === 'development',
    serverPort: 0
}

if (!sharedObject.isDev) {
    // 检测端口是否被占用
    const portIsOccupied = (port: number): Promise<number> => {
        return new Promise(r => {
            const validate = (p: number) => {
                const server: http.Server = http
                    .createServer()
                    .listen(p)
                    .on('listening', () => {
                        server.close()
                        r(p)
                    })
                    .on('error', (err: any) => {
                        if (err.code === 'EADDRINUSE') {
                            server.close()
                            validate(p += 1)
                        }
                    })
            }
            validate(port)
        })
    }
    // 执行
    portIsOccupied(8981)
        .then((p) => {
            sharedObject.serverPort = p
            http.createServer((req, res) => {
                if (req.url === '/') {
                    return fs.readFile(path.resolve(__dirname, '..', 'index.html'), (err, data) => {
                        if (err) return
                        res.setHeader('content-type', 'text/html; charset=utf-8')
                        res.end(data)
                    })
                } else {
                    return fs.readFile(path.resolve(__dirname, '..', '.' + req.url), (err, data) => {
                        console.log(err);

                        if (err) return
                        if (req.url!.endsWith('.js')) {
                            res.setHeader('content-type', 'application/javascript')
                        } else if (req.url!.endsWith('.css')) {
                            res.setHeader('content-type', 'text/css')
                        } else if (req.url!.endsWith('.html')) {
                            res.setHeader('content-type', 'text/html; charset=utf-8')
                        }
                        // 缓存7天
                        res.setHeader('cache-control', 'max-age=604800')
                        res.end(data)
                    })
                }
            })
                .listen(p)
        })

}

const resolveUrl = (address: string) => `http://localhost:${sharedObject.isDev ? 3000 : sharedObject.serverPort}/#${address}`

export function createMainWindow(): BrowserWindow {
    const { width, height } = screen.getPrimaryDisplay().workAreaSize;
    const win = new BrowserWindow({
        width, height, webPreferences: {
            // preload: path.join(__dirname, "preload.js"),
            nodeIntegration: true,
            contextIsolation: false,
        }
    });
    const url = resolveUrl("");
    console.log(url);

    win.loadURL(url);
    return win;
}